<script setup>
import { ref, onMounted } from "vue";
import { submit, save, statistics, rollback } from "@/api/2d";
import { useCounterStore } from "@/stores/counter";
import { storeToRefs } from "pinia";
const store = useCounterStore();

const {
  createTime,
  dataList,
  idsList,
  changeKeyIdList,
  changeKeyList,
  lastSubmitTime,
  lastChangeKeyNum,
  noOperationNum,
  workPackId,
  list,
  sign,
  rollbackKeys,
} = storeToRefs(store);
const help = () => {
  dialogVisible.value = true;
};
const dialogVisible = ref(false);

const handleClose = (done) => {
  dialogVisible.value = false;
};

const tableData = [
  {
    label: "切换分级",
    value: "1 2 3 4 5",
  },
  {
    label: "切换颜色",
    value: "Q W E R T",
  },
  {
    label: "切换页面",
    value: "A/D",
  },
  {
    label: "全选/非全选",
    value: "ctrl + a/ ctrl + d",
  },
];
function timeDifference(d1, d2) {
  // 确保输入是有效的日期对象
  if (!(d1 instanceof Date) || !(d2 instanceof Date)) {
    console.error("参数必须是有效的日期对象");
    return null;
  }
  var t2 = d2.getTime(); // 获取第二个日期的时间戳（毫秒）
  var t1 = d1.getTime(); // 获取第一个日期的时间戳（毫秒）
  var diffMS = Math.abs(t2 - t1); // 计算绝对值，避免负数
  // 将差值从毫秒转换为分钟
  var diffMinutes = Math.floor(diffMS / (60 * 1000));
  return diffMinutes;
}

const add = () => {
  submitSave();
  submitStatistics();
  submitDialogVisible.value = true;
};
const submitSave = () => {
  save(
    {
      workPackId: workPackId.value,
      submitType: 0,
      dataList: dataList.value,
    },
    sign.value
  );
};
const submitStatistics = () => {
  let time = timeDifference(createTime.value, new Date());
  // console.log(time, "time");
  let everyItemList = [];
  let readItemList = [];
  const markIdList = [];
  const everyMarkIdList = [];
  totalFiles.value = [];
  totalInspections.value = [];
  list.value.forEach((i) => {
    everyMarkIdList.push(...i.labelList, i.labelKey);
    totalFiles.value.push(...i.labelList, i.labelKey);
    if (idsList.value.includes(i.id)) {
      if (!markIdList.includes(i.materialId)) {
        markIdList.push(i.materialId);
      }
      readItemList.push(...i.labelList, i.labelKey);
      totalInspections.value.push(...i.labelList, i.labelKey);
    }
  });
  const countMap = {};
  readItemList.forEach((item) => {
    countMap[item] = (countMap[item] || 0) + 1;
  });
  const changeCountMap = {};

  changeKeyList.value.forEach((i) => {
    changeCountMap[i] = (changeCountMap[i] || 0) + 1;
  });
  everyMarkIdList.forEach((i) => {
    everyItemList[i] = (everyItemList[i] || 0) + 1;
  });

  const allKeys = new Set([
    ...Object.keys(everyItemList),
    ...Object.keys(countMap),
    ...Object.keys(changeCountMap),
  ]);

  // 创建结果数组
  const result = [];

  allKeys.forEach((key) => {
    // 初始化默认值为0，确保即使某个对象中没有该键，也能正确计算
    const count = everyItemList[key] || 0;
    const checkCount = countMap[key] || 0;
    const modifyCount =
      changeCountMap[key] !== undefined ? changeCountMap[key] : 0;

    // 添加到结果数组
    result.push({
      key: key,
      count: count,
      modifyCount: modifyCount,
      checkCount: checkCount,
    });
  });
  let workFileCount = 0;
  if (lastChangeKeyNum.value && lastChangeKeyNum.value.length > 0) {
    workFileCount = countElementsNotInB(markIdList, lastChangeKeyNum.value);
  }

  form.value = {
    workPackId: workPackId.value,
    preObjectCount: -1,
    preObjectQualifiedCount: -1,
    manualCount: changeKeyIdList.value.length,
    totalWorkDuration: time,
    totalWorkFileCount: markIdList.length,
    workDuration: timeDifference(lastSubmitTime.value, new Date())
      ? timeDifference(lastSubmitTime.value, new Date())
      : 0,
    workFileCount: 0,
    noOperationNum: noOperationNum.value,
    objectCountList: result,
  };

  statistics(form.value, sign.value);
  lastChangeKeyNum.value = markIdList;
  lastSubmitTime.value = new Date();
};

function countElementsNotInB(a, b) {
  // 将数组 b 转换为 Set，以便快速查找
  const setB = new Set(b);

  // 过滤数组 a，找出所有不在 setB 中的元素
  const notInB = a.filter((item) => !setB.has(item));

  // 返回这些元素的数量
  return notInB.length;
}

const desc = ref("");
const submitForm = async () => {
  await submit(
    {
      workPackId: workPackId.value,
      desc: desc.value,
      objectCountList: form.value.objectCountList,
    },
    sign.value
  ).then((res) => {
    if (res.data.code == 500 || res.data.code == 1001) {
      ElMessage.error(res.data.msg);
      return;
    }
    window.close();
    submitDialogVisible.value = false;
  });
};

const onRollback = async () => {
  submitSave();
  submitStatistics();
  await rollback(
    {
      passKeys: [],
      rollbackKeys: rollbackKeys.value,
      workPackId: workPackId.value,
      desc: desc.value,
      objectCountList: form.value.objectCountList,
    },
    sign.value
  ).then((res) => {
    if (res.data.code == 500 || res.data.code == 1001) {
      ElMessage.error(res.data.msg);
      return;
    }
    ElMessage.success("打回成功");
  });
};
const submitDialogVisible = ref(false);
const form = ref();

const submitHandleClose = (done) => {
  desc.value = "";
  // submitDialogVisible.value = false;
};
const totalFiles = ref();
const totalInspections = ref();
onMounted(() => {
  setInterval(() => {
    submitSave();
    submitStatistics();
  }, 600000);
});
</script>

<template>
  <div class="menu flex-y-end mt-10">
    <el-button type="success" class="w-120" @click="add">通过</el-button>
    <el-button type="danger" class="w-120" @click="onRollback">打回</el-button>
    <el-button type="text" class="w-100" style="color: white"
      >功能设置</el-button
    >
    <el-button type="text" class="w-100" style="color: white">查看 </el-button>
    <el-button type="text" @click="help" class="w-100" style="color: white"
      >帮助
    </el-button>
  </div>

  <el-dialog
    v-model="dialogVisible"
    title="帮助指南"
    close-on-click-modal
    width="500"
    :before-close="handleClose"
  >
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="label" label="功能 " />
      <el-table-column prop="value" label=" 快捷键" />
    </el-table>
  </el-dialog>

  <el-dialog
    v-model="submitDialogVisible"
    title="提交数据"
    close-on-click-modal
    width="600"
    :close="submitHandleClose"
  >
    <div style="width:100%,height:100%" class="flex-center">
      <el-form center :model="form" label-width="auto" style="width: 400px">
        <el-form-item label="文件总数:"
          ><span class="f-12"> {{ totalFiles.length }} 个</span>
        </el-form-item>
        <el-form-item label="质检数量:">
          {{ totalInspections.length }}个
        </el-form-item>
        <el-form-item label="消耗时长:">
          {{ form.totalWorkDuration }} 分
        </el-form-item>
        <!-- <el-form-item label="标记合格率:"> {{ form.name }} </el-form-item> -->

        <el-form-item label="结论备注:">
          <el-input v-model="desc" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()"> 提交 </el-button>
          <el-button @click="submitDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.menu {
  width: 100%;
}
</style>
